package boss.portal.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import boss.portal.util.RSaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import boss.portal.constant.ConstantKey;
import boss.portal.exception.TokenException;
import boss.portal.service.impl.GrantedAuthorityImpl;

public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
	
	public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new TokenException("Token为空");
        }
        // parse the token.
        String user = null;

        Map<String,String> resultMap = RSaUtil.volidToken(token.replaceAll("Bearer ", ""));
        String account = resultMap.get("account");
        String subject = resultMap.get("subject");
        String issuer = resultMap.get("issuer");
        if (subject != null) {
            String[] split = subject.split("-")[1].split(",");
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            for (int i=0; i < split.length; i++) {
                authorities.add(new GrantedAuthorityImpl(split[i]));
            }
            return new UsernamePasswordAuthenticationToken(user, null, authorities);
        }
        return null;
    }

}
